package com.luoshenshen.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ShenshenLuo
 * @date 2025/4/14 0:07
 **/
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static Map<String, Channel> channelMap = new HashMap<String, Channel>();

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String format = sdf.format(new Date());
        System.out.println(format + socketAddress + " 上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String format = sdf.format(new Date());
        System.out.println(format + socketAddress + " 下线了");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String format = sdf.format(new Date());
        channels.writeAndFlush(format + " [客户端]: " + socketAddress + " 加入聊天");
        channels.add(channel);
        channelMap.put(socketAddress.toString(), channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String format = sdf.format(new Date());
        channels.writeAndFlush(format + " [客户端]: " + socketAddress + " 离开聊天");
        channels.remove(channel);
        channelMap.remove(socketAddress.toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        ChannelPipeline pipeline = ctx.channel().pipeline();
        Channel channel = ctx.channel();
        channels.forEach(item -> {
            if (item != channel) {
                item.writeAndFlush("客户:" + item.remoteAddress() + "发送消息: " + msg);
            }else {
                item.writeAndFlush("自己:" + item.remoteAddress() + "发送消息: " + msg);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();
    }
}
